package com.huatai.datadevelop.thread.service;

import cn.hutool.core.util.ObjectUtil;
import com.huatai.datadevelop.utils.JDBCUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.sql.*;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * @author hecai
 * @description: TODO  异步线程  数据入库操作
 * 参考地址  https://blog.csdn.net/Tir_zhang/article/details/125930870
 * @date 2022/12/19 15:59
 * @Version 1.0
 */
@Slf4j
@Service
public class InsertDataBaseExecutor {

    /**
     * 数据异步入库 多条
     *
     * @param fetchDataList 接口数据
     * @param field         库表字段  不包含id
     */
    @Async("asyncServiceExecutor")
    @Transactional(rollbackFor = Exception.class)
    public void insertDataArrayList(List<Object> fetchDataList, String field, String tableName,String updateColumnName,List<String> newestDataByColumn) {
        Connection connection = JDBCUtils.getConnection();
        PreparedStatement ps = null;
        String[] fieldSplit = field.split(",");
        int length = fieldSplit.length;
        String value = "";
        for (int i = 0; i < length; i++) {
            value = value + "?,";
        }
        String sql = "insert into " + tableName + "(" + field + ")" + " values" + "(" + value.substring(0, value.length() - 1) + ")";
        try {
            //不允许自动提交数据
            connection.setAutoCommit(false);
            connection.prepareStatement(sql);
            ps = connection.prepareStatement(sql);
            for (int i = 0; i < fetchDataList.size(); i++) {
                Boolean updateBoolean = Boolean.FALSE;
                Object fetchData = fetchDataList.get(i);
                if (fetchData != null) {
                    for (int j = 0; j < fieldSplit.length; j++) {
                        String dataValue = "";
                        Object data = ((LinkedHashMap) fetchData).get(fieldSplit[j]);
                        if (ObjectUtil.isNotNull(data)) {
                            //判断是否是增量更新的内容
                            if(StringUtils.isNotBlank(updateColumnName)){
                                Object o = ((LinkedHashMap) fetchData).get(updateColumnName);
                                if(o!=null){
                                    String oStr = o.toString();
                                    //不包含则更新
                                    if(!newestDataByColumn.contains(oStr)){
                                        updateBoolean = Boolean.TRUE;
                                    }
                                }
                            }
                            //全量更新
                            else {
                                updateBoolean = Boolean.TRUE;
                            }
                            dataValue = data.toString();
                        }
                        ps.setString(j + 1, dataValue);
                    }
                    //1、“攒”sql
                    if(updateBoolean){
                        ps.addBatch();
                    }
                }
            }
            //2、执行batch
            ps.executeBatch();
            connection.commit();
            log.info("数据入库成功!!");
        } catch (SQLException e) {
            log.error("数据入库失败，失败原因：" + e.getMessage());
            try {
                log.info("事务尝试回滚");
                connection.rollback();
            } catch (SQLException ex) {
                log.error("事务回滚失败");
            }
            log.error("事务回滚成功");
        } finally {
            JDBCUtils.close(ps, connection);
        }
    }

    /**
     * 数据操作入库 单条
     *
     * @param fetchData
     * @param field
     * @param tableName
     */
    @Async("asyncServiceExecutor")
    @Transactional(rollbackFor = Exception.class)
    public void insertDataLinkedHashMap(Object fetchData, String field, String tableName) {
        Connection connection = JDBCUtils.getConnection();
        PreparedStatement ps = null;
        String[] fieldSplit = field.split(",");
        int length = fieldSplit.length;
        String value = "";
        for (int i = 0; i < length; i++) {
            value = value + "? ";
        }
        String sql = "insert into " + tableName + "(field) values(value)";
        //不允许自动提交数据
        try {
            connection.setAutoCommit(false);
            connection.prepareStatement(sql);
            for (int j = 0; j < fieldSplit.length; j++) {
                String dataValue = "";
                Object data = ((LinkedHashMap) fetchData).get(fieldSplit[j]);
                if (ObjectUtil.isNotNull(data)) {
                    dataValue = data.toString();
                }
                ps.setString(j + 1, dataValue);
            }
            //1、“攒”sql
            ps.addBatch();
            //2、执行batch
            ps.executeBatch();
            connection.commit();
        } catch (Exception e) {
            log.error("数据入库失败，失败原因：" + e.getMessage());
            try {
                log.info("事务尝试回滚");
                connection.rollback();
            } catch (SQLException ex) {
                log.error("事务回滚失败");
            }
        } finally {
            JDBCUtils.close(ps, connection);

        }
    }
}
